package  
{
	import org.flixel.*;
	
	/**
	 * ...
	 * @author J W
	 */
	public class PlayerGun extends FlxSprite 
	{
		public static var firing:Boolean = false;
		public var aimAngle:Number = 0; //This variable is public so the playstate can look it up for our text objects.
		
		private var _firePoint:FlxPoint;
		private var _gunFacingRight:Boolean;
		private var _state:PlayState;
		
		public function PlayerGun(X:Number, Y:Number) 
		{
			super(X, Y);
			
			_gunFacingRight = true;
			
			_firePoint = new FlxPoint();
			_state = FlxG.state as PlayState;
			
			loadGraphic(ImageFiles.gunArm, false, true, 20, 10);
			//createGraphic(1, 1, 0x00000000);
			//this.antialiasing = true;
			origin = new FlxPoint(1, 5);
			
			addAnimation("left", [1]);
			addAnimation("right", [0]);
		}
		
		override public function update():void
		{
			FlxU.rotatePoint(x + FlxG.scroll.x + width, y + FlxG.scroll.y + height / 2, x + FlxG.scroll.x + origin.x, y + FlxG.scroll.y + origin.y, aimAngle, _firePoint);
			//_firePoint.x = this.x  + FlxG.scroll.x + Math.cos(aimAngle * Math.PI / 180) * width;
			//_firePoint.y = this.y  + FlxG.scroll.y + 5 + Math.sin(aimAngle * Math.PI / 180) * width;
			
			setAimAngle();
			this.angle = this.aimAngle;
			
			// Fire lightning on mouse click
			if ((FlxG.mouse.justPressed()) && (PowerGauge.currentVolts > PowerGauge.THRESHOLD) && (!isOverMuteButton()) && (!isOverPauseButton()))
			{
				firing = true;
			}
			else if ((FlxG.mouse.justPressed()) && !(PowerGauge.currentVolts > PowerGauge.THRESHOLD))
			{
				FlxG.play(SoundFiles.noPowerSound);
			}
			
			if (FlxG.mouse.justReleased())
			{
				firing = false;
			}
			
			if (firing)
			{
				if (PowerGauge.currentVolts <= PowerGauge.MINVOLTS)
				{
					firing = false;
				}
				_state.lightning.Fire(_firePoint, new FlxPoint(FlxG.mouse.screenX, FlxG.mouse.screenY));
			}
			else
			{
				_state.lightning.StopFiring();
			}
			
			if (_gunFacingRight)
			{
				play("right");
			}
			else
			{
				play("left");
			}
			
			super.update();
		}
		
		private function setAimAngle():void
		{
			//this.aimAngle = FlxMath.asDegrees(FlxMath.atan2((FlxG.mouse.y - (y + (height / 2))), (FlxG.mouse.x - (x + width / 2))));
			this.aimAngle = FlxU.getAngle((FlxG.mouse.x - (x + (width / 2))), (FlxG.mouse.y - (y + (height / 2))));
		}
		
		//Sets facing to LEFT
		public function setFacingLeft():void
		{
			_gunFacingRight = false;
		}
		
		//Sets facing to RIGHT
		public function setFacingRight():void
		{
			_gunFacingRight = true;
		}
		
		protected function isOverPauseButton():Boolean
		{
			return _state.pauseButton.overlapsPoint(FlxG.mouse.x, FlxG.mouse.y);
		}
		
		protected function isOverMuteButton():Boolean
		{
			return _state.soundButton.overlapsPoint(FlxG.mouse.x, FlxG.mouse.y);
		}
	}
}